package cn.yhjz.platform.system.controller;

import cn.yhjz.common.util.IdUtil;
import cn.yhjz.platform.system.entity.SysUser;
import cn.yhjz.platform.system.service.ISysDeptService;
import cn.yhjz.platform.system.entity.SysDept;
import cn.yhjz.platform.system.service.ISysUserService;
import cn.yhjz.platform.system.util.LoginUtil;
import cn.yhjz.platform.system.vo.SysDeptVo;
import cn.yhjz.common.AjaxResponse;
import cn.hutool.core.collection.CollUtil;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/system/dept")
@PreAuthorize("hasAuthority('system:dept')")
public class SysDeptController {

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @PostMapping("/list")
    public List<SysDeptVo> list(@RequestBody SysDept sysDept) {
        return sysDeptService.select(sysDept);
    }

    @PostMapping("/page")
    public AjaxResponse page(@RequestBody SysDeptVo vo) {
        SysDept entity = new SysDept();
        BeanUtils.copyProperties(vo, entity);
        return AjaxResponse.success(sysDeptService.getPage(vo.getCurrentPage(), vo.getPageSize(), entity));
    }

    @PostMapping("/addOrUpdate")
    public AjaxResponse add(@RequestBody SysDept entity) {
        if (entity.getId() != null) {
            entity.setUpdatedBy(LoginUtil.getCurrentUser().getUserCode());
            entity.setUpdatedTime(new Date());
            return AjaxResponse.success(sysDeptService.updateById(entity));
        } else {
            entity.setDeptCode(IdUtil.generate());
            entity.setCreatedBy(LoginUtil.getCurrentUser().getUserCode());
            entity.setCreatedTime(new Date());
            return AjaxResponse.success(sysDeptService.insert(entity));
        }
    }

    @GetMapping("/selectById")
    public AjaxResponse selectById(Long id) {
        return AjaxResponse.success(sysDeptService.selectById(id));
    }

    @DeleteMapping("/deleteById")
    public AjaxResponse deleteById(Long id) {
        SysDeptVo dept = sysDeptService.selectById(id);
        //先判断是否还有用户绑定在此部门上
        SysUser userParam = new SysUser();
        userParam.setDeptCode(dept.getDeptCode());
        List<SysUser> userList = sysUserService.select(userParam);
        if (CollUtil.isNotEmpty(userList)) {
            return AjaxResponse.fail("此部门下还有用户，不可删除");
        }
        //检查此部门还有没有子部门
        SysDept deptParam = new SysDept();
        deptParam.setParentCode(dept.getDeptCode());
        List<SysDeptVo> children = sysDeptService.select(deptParam);
        if (CollUtil.isNotEmpty(children)) {
            return AjaxResponse.fail("此部门下还有子部门，不可删除");
        }
        return AjaxResponse.success(sysDeptService.deleteById(id));
    }

    /**
     * 返回部门的树
     *
     * @return
     */
    @PostMapping("/loadDeptTree")
    public AjaxResponse loadDeptTree() {
        List<SysDeptVo> sysDeptVoList = this.sysDeptService.select(null);
        List<SysDeptVo> baseVoList = buildTree(sysDeptVoList);
        return AjaxResponse.success(baseVoList);
    }

    /**
     * 把列表整理成树形结构
     *
     * @param sysDeptVoList
     * @return
     */
    public static List<SysDeptVo> buildTree(List<SysDeptVo> sysDeptVoList) {
        for (SysDeptVo sysDeptVo : sysDeptVoList) {
            for (SysDeptVo sysDeptVoInner : sysDeptVoList) {
                if (StrUtil.equals(sysDeptVoInner.getParentCode(), sysDeptVo.getDeptCode())) {
                    if (CollUtil.isEmpty(sysDeptVo.getChildren())) {
                        sysDeptVo.setChildren(new ArrayList<>());
                    }
                    sysDeptVo.getChildren().add(sysDeptVoInner);
                }
            }
        }
        List<SysDeptVo> baseList = new ArrayList<>();
        for (SysDeptVo sysDeptVo : sysDeptVoList) {
            if ("root".equals(sysDeptVo.getParentCode()) || StrUtil.isBlank(sysDeptVo.getParentCode())) {
                baseList.add(sysDeptVo);
            }
        }
        return baseList;
    }
}
